package cn.enjoy.tool.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class JwtUtil {
    public static String SIGN_KEY = "DK";
    public static String BEARER = "bearer";
    public static Integer AUTH_LENGTH = 7;
    public static String BASE64_SECURITY;

    static {
        // 加密 DK
        BASE64_SECURITY = Base64.getEncoder().encodeToString(SIGN_KEY.getBytes(StandardCharsets.UTF_8));
    }
    public static String getToken(String auth) {
        if (auth != null && auth.length() > AUTH_LENGTH) {
            String headStr = auth.substring(0,6).toLowerCase();
            if (headStr.equals(BEARER)) {
                return auth.substring(7);
            }
            return null;
        } else {
            return null;
        }
    }

    // 解析JWT
    public static Claims parseJWT(String jsonWebToken) {
        try {
            return (Claims)Jwts.parser().setSigningKey(Base64.getDecoder().decode(BASE64_SECURITY)).parseClaimsJws(jsonWebToken).getBody();
        } catch (Exception var) {
            return null;
        }
    }
}
